package com.syj.qdp.framework.common.validation;

import com.syj.qdp.framework.common.enums.InEnum;
import com.syj.qdp.framework.common.core.IntArrayValuable;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Lyon
 */
public class InEnumValidator implements ConstraintValidator<InEnum, Integer> {

    private List<Integer> values;

    @Override
    public void initialize(InEnum inEnum) {
        IntArrayValuable[] enumConstants = inEnum.value().getEnumConstants();
        if (enumConstants.length == 0) {
            values = Collections.emptyList();
        } else {
            values = Arrays.stream(enumConstants[0].array()).boxed().collect(Collectors.toList());
        }
    }

    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        boolean valid = value != null && values.contains(value);
        if (!valid) {
            // 禁用默认的错误消息
            context.disableDefaultConstraintViolation();
            // 重新构建错误消息
            context.buildConstraintViolationWithTemplate(
                    context
                            .getDefaultConstraintMessageTemplate()
                            .replace("\\{value}", values.toString())
            ).addConstraintViolation();
        }
        return valid;
    }
}
